/** 
  基地考核
*/
<template>
  <div>
    <condition-card ref="baseAssessCondition" @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.examinationBatch')">
            <el-select v-model="queryForm.condition.batch" clearable style="width: 100%">
              <el-option
                v-for="item in options.batch"
                :key="item.id"
                :label="item.batch"
                :value="item.batch">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssess.internshipBaseName')">
            <el-input v-model="queryForm.condition.baseName" clearable :maxlength="64" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.baseLevel')">
            <el-select v-model="queryForm.condition.baseLevel" clearable style="width: 100%">
              <el-option
                v-for="item in options.baseLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.currentStauts')">
            <el-select v-model="queryForm.condition.status" clearable style="width: 100%">
              <el-option
                v-for="item in options.status"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssess.averageBegin')">
            <el-input v-model="queryForm.condition.averageBegin" clearable :maxlength="8" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssess.averageEnd')">
            <el-input v-model="queryForm.condition.averageEnd" clearable :maxlength="8" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{ $t('baseAssess.baseAssessList') }}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-right" style="display: flex;">
          <el-button v-if="permitToExport" @click="exportBaseAssess">{{$t('common.btn.export')}}</el-button>
        </div>
      </div>
      <edu-table :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
        <edu-table-column :label="$t('baseAssessSetting.examinationBatch')" prop="batch"></edu-table-column>
        <edu-table-column :label="$t('baseAssess.internshipBaseName')" prop="baseName"></edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.baseLevel')" prop="baseLevelName"></edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.materialSubmissionTime')" prop="submitMaterialsTime">
          <template slot-scope="scope">
            {{ scope.row.submitMaterialsStart }} {{ $t('graduateBase.to') }} {{ scope.row.submitMaterialsEnd }}
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.onSiteAssessTime')" prop="onSiteExamineTime">
          <template slot-scope="scope">
            {{ scope.row.onSiteExamineStart }} {{ $t('graduateBase.to') }} {{ scope.row.onSiteExamineEnd }}
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.ratingTime')" prop="scoreTime">
          <template slot-scope="scope">
            {{ scope.row.scoreStart }} {{ $t('graduateBase.to') }} {{ scope.row.scoreEnd }}
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('baseAssess.average')" prop="average"></edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.currentStauts')" prop="status">
          <template slot-scope="scope">
            <div class="status-container">
              <el-button v-if="scope.row.status === 0" type="info" plain>{{ scope.row.status | status }}</el-button>
              <el-button v-else-if="scope.row.status === 1" type="warning" plain>{{ scope.row.status | status }}</el-button>
              <el-button v-else type="success" plain>{{ scope.row.status | status }}</el-button>
            </div>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('common.text.operation')" fit width="200">
          <template slot-scope="scope">
            <el-button v-if="permitToEdit" type="text" @click="editBaseAssess(scope.row)">{{$t('common.btn.edit')}}</el-button>
            <el-button v-if="permitToScore" type="text" @click="scoreBaseAssess(scope.row)">{{$t('graduateBase.score')}}</el-button>
            <el-button v-if="permitToScoreDetail" type="text" @click="selectBaseAssessScoreDetail(scope.row)">{{$t('baseAssess.scoreDetails')}}</el-button>
            <el-button v-if="permitToDetail" type="text" @click="selectBaseAssessDetail(scope.row)">{{$t('graduateBase.details')}}</el-button>
          </template>
        </edu-table-column>
      </edu-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryForm.pageNum_"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="queryForm.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryForm.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <!-- 编辑开始 -->
    <el-dialog
      :before-close="beforeClose"
      width="70%"
      :title="$t('baseAssess.baseAssess')"
      class="base-assess-set-dialog"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
        <edit-submit-material ref="submitMaterail" 
        @close-edit-dialog="closeEditDialog"
        @refresh-base-assess="reset"
        :submitMaterialInfo="submitMaterialInfo">
      </edit-submit-material>
    </el-dialog>
    <!-- 编辑结束 -->
    <!-- 评分开始 -->
    <el-dialog
      :before-close="beforeCloseScore"
      width="70%"
      :title="$t('baseAssess.baseAssess')"
      class="base-assess-set-dialog"
      :visible.sync="scoreDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
        <experts-score ref="expertsScore" @close-edit-dialog="closeScoreDialog" :expertsScoreInfo="expertsScoreInfo"></experts-score>
    </el-dialog>
    <!-- 评分结束 -->
    <!-- 评分详情开始 -->
    <el-dialog
      @close="detailScoreDialogVisible = false"
      width="70%"
      :title="$t('baseAssess.baseAssessDetail')"
      class="base-assess-set-dialog"
      :visible.sync="detailScoreDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
        <base-assess-score-details ref="baseAssessDetail" 
        :detailScoreAssessBaseInfo="detailScoreAssessBaseInfo"
        @close-detail-dialog="closeScoreDetailDialog" 
        @export-base-assess-detail="exportBaseAssessDetail">
        </base-assess-score-details>
    </el-dialog>
    <!-- 评分详情结束 -->
    <!-- 详情开始 -->
    <el-dialog
      @close="detailDialogVisible = false"
      width="70%"
      :title="$t('baseAssess.baseAssessDetail')"
      class="base-assess-set-dialog"
      :visible.sync="detailDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
        <base-assess-details ref="baseAssessDetail" 
        :detailAssessBaseInfo="detailAssessBaseInfo"
        :scoreStatus="scoreStatus"
        @close-detail-dialog="closeDetailDialog" 
        @export-base-assess-detail="exportBaseAssessDetail">
        </base-assess-details>
    </el-dialog>
    <!-- 详情结束 -->
    <edu-export-dialog
      :disabled="exportButton"
      :title="$t('message.prompt')"
      ref="downloadRef"
      :data="exportResult">
    </edu-export-dialog>
  </div>
</template>
<script>
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
import editSubmitMaterial from './editSubmitMaterial';
import expertsScore from './expertsScore';
import baseAssessScoreDetails from './baseAssessScoreDetails';
import baseAssessDetails from './baseAssessDetails';
export default {
  components: {
    'edit-submit-material': editSubmitMaterial,
    'experts-score': expertsScore,
    'base-assess-score-details': baseAssessScoreDetails,
    'base-assess-details': baseAssessDetails
  },
  data () {
    return {
      auths: [],
      userInfo: {},
      permitToExport: false,
      permitToEdit: false,
      permitToScore: false,
      permitToScoreDetail: false,
      permitToDetail: false,
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          batch: '', // 考核批次
          baseName: '', // 实习基地名称
          baseLevel: '', // 基地级别
          status: '', // 当前状态
          averageBegin: '', // 考核得分起
          averageEnd: '' // 考核得分止
        }
      },
      dataList: [],
      exportButton: false,
      exportResult: null,
      indexKey: '1', // 面包屑
      title: '',
      multipleSelection: [],
      options: {
        // 考核批次
        batch: [],
        // 基地级别
        baseLevel: [
          {
            label: '校级',
            value: '1'
          },
          {
            label: '院级',
            value: '2'
          }
        ],
        // 当前状态
        status: [
          {
            label: '未提交',
            value: '0'
          },
          {
            label: '待评分',
            value: '1'
          },
          {
            label: '已评分',
            value: '2'
          }
        ],
        
      },
      dialogMode: 'add',
      submitMaterialInfo: {},
      dialogVisible: false,
      dialogMultipleSelection: [],
      scoreDialogVisible: false,
      expertsScoreInfo: {},
      detailScoreDialogVisible: false,
      detailDialogVisible: false,
      detailAssessBaseInfo: {},
      detailScoreAssessBaseInfo: {},
      scoreStatus: 0
    }
  },
  filters: {
    status(val) {
      switch (val) {
        case 0:
          return '未提交'
        case 1:
          return '待评分'
        case 2:
        return '已评分'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    let sessiondata = JSON.parse(localStorage.getItem("sessiondata"))
    if (sessiondata) {
      if (sessiondata.auths) {
        this.auths = sessiondata.auths
      }
      if (sessiondata.mockUser || sessiondata.user) {
        this.userInfo = sessiondata.mockUser || sessiondata.user
      }
    }
    graduateStudentApi.queryPublishedAssessBatch().then(res => {
      this.options.batch = res.data
    })
    graduateStudentApi.queryBaseAssessData(this.queryForm).then(res => {
      this.dataList = res.data.list
      this.queryForm.total_ = res.data.total_
    })
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    // 改变基地级别
    changeBaseLevel(val) {
      this.queryForm.condition.templateId = ''
      graduateStudentApi.assessmentTempSetList({
        "pageNum_": "1",
        "pageSize_": "0",
        "condition": {
          "baseLevel": val
        }
      }).then(res => {
        this.options.templateId = res.data.list
      })
    },
    reset() {
      Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '')
      this.onSubmit()
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    getListData() {
      this.queryForm.condition.baseName = this.queryForm.condition.baseName.trim()
      this.queryForm.condition.averageBegin = this.queryForm.condition.averageBegin.trim()
      this.queryForm.condition.averageEnd = this.queryForm.condition.averageEnd.trim()
      let expReg = /^(\d{0,3})(\.\d{1,2})?$/ 
      if (!expReg.test(this.queryForm.condition.averageBegin) || Number(this.queryForm.condition.averageBegin) > 100) {
        this.$eduAlert(this.$t('baseAssess.validateScore'), this.$t('graduateBase.prompt'), {
          type: 'warning'
        })
        return
      }
      if (!expReg.test(this.queryForm.condition.averageEnd) || Number(this.queryForm.condition.averageEnd) > 100) {
        this.$eduAlert(this.$t('baseAssess.validateScore'), this.$t('graduateBase.prompt'), {
          type: 'warning'
        })
        return
      }   
      graduateStudentApi.queryBaseAssessData(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total_
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        let currentIds = []
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id)
          })
        }
        graduateStudentApi.exportBaseAssessData({
          "baseLevel": this.queryForm.condition.baseLevel,
          "baseName": this.queryForm.condition.baseName,
          "batch": this.queryForm.condition.batch,
          "averageBegin": this.queryForm.condition.averageBegin,
          "averageEnd": this.queryForm.condition.averageEnd,
          "status": this.queryForm.condition.status,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close()
            this.exportButton = false
            this.normalDelayRequest(res.key, res.msg)
          } else {
            this.cycleToGetKey()
          }
        })
      }, 3000)
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        graduateStudentApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data
          if (res.code == 200 && res.data.status) {
            this.exportButton = false
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name
            // window.open(path);
            window.location.href = path
            this.$message.success(this.$t('result.exportSuccessfully'))
            this.$refs.downloadRef.close()
          } else {
            this.delayRequest(key, name)
          }
        })
      }, 3000)
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        graduateStudentApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data
          if (res.code == 200 && res.data.status) {
            this.exportButton = false
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name
            // window.open(path);
            window.location.href = path
            this.$message.success(this.$t('result.exportSuccessfully'))
            this.$refs.downloadRef.close()
          } else {
            this.delayRequest(key, name)
          }
        })
      }, 3000)
    },
    // 导出基地考核设置
    exportBaseAssess() {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null
      this.$refs.downloadRef.open()
      this.exportButton = true
      this.cycleToGetKey()
    },
    // 关闭x事件（编辑弹出框）
    beforeClose: function (done) {
      // this.$refs['submitMaterail'].uploadConfig.fileList = [];
      this.$refs['submitMaterail'].back()
    },
    // 取消
    cancel() {
      let allIsEmpty = true
      for (let key in this.dialogForm) {
        if (this.dialogForm[key]) {
          allIsEmpty = false
        }
      }
      if (allIsEmpty) {
        this.innerVisible = false
        this.dialogVisible = false
      } else {
        this.innerVisible = true
      }
    },
    handleDialogSelectionChange(val) {
      this.dialogMultipleSelection = val
    },
    // 关闭编辑弹出框
    closeEditDialog() {
      this.$refs['submitMaterail'].fileList = []
      this.$refs['submitMaterail'].$refs['form'].resetFields()
      this.dialogVisible = false
    },
    // 编辑基地考核（材料报送）--表格
    async editBaseAssess(row) {
      if (row.status !== 0) {
        this.$message.info(this.$t('baseAssess.disabledToEdit'))
        return
      }
      if (row.submitMaterialsStart && row.submitMaterialsEnd) {
        let submitMaterialsStart = row.submitMaterialsStart.replace(/-/g, '/')
        let submitMaterialsEnd = row.submitMaterialsEnd.replace(/-/g, '/')
        let startTime = new Date(submitMaterialsStart).getTime()
        let endTime = new Date(submitMaterialsEnd).getTime()
        let nowTimeResponse = await graduateStudentApi.getCurrentSystemTime()
        if (nowTimeResponse.data) {
          nowTimeResponse.data = new Date(nowTimeResponse.data).getTime()
        }
        if (!(nowTimeResponse.data >= startTime && nowTimeResponse.data <= endTime)) {
          this.$eduConfirm(this.$t('baseAssess.submitMaterialTime') + ':' + row.submitMaterialsStart + '~' + row.submitMaterialsEnd + ',' + this.$t('baseAssess.notContainTime')).then(_ => {})
          return
        }
        this.dialogMode = 'edit'
        const response = await graduateStudentApi.queryBaseAssessDetailById(row.id)
        if (response.code === 200) {
          this.submitMaterialInfo = response.data
        }
        this.dialogVisible = true
      }
    },
    // 删除基地考核设置操作
    deleteBaseAssessSettingRow(id) {
      graduateStudentApi.removeBaseAssessSet({
        "id": id
      }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('common.tips.deleteSuccess'))
          this.onSubmit()
        }
      });
    },
    // 专家评分--表格
    async scoreBaseAssess(row) {
      if (row.status === 2) {
        this.$message.info(this.$t('baseAssess.disabledToScore'))
        return
      }
      if (row.scoreStart && row.scoreEnd) {
        let scoreStart = row.scoreStart
        let scoreEnd = row.scoreEnd
        let startTime = new Date(scoreStart.replace(/-/g, '/')).getTime()
        let endTime = new Date(scoreEnd.replace(/-/g, '/')).getTime()
        let nowTimeResponse = await graduateStudentApi.getCurrentSystemTime()
        if (nowTimeResponse.data) {
          nowTimeResponse.data = new Date(nowTimeResponse.data).getTime()
        }
        if (!(nowTimeResponse.data >= startTime && nowTimeResponse.data <= endTime)) {
          this.$eduConfirm(this.$t('baseAssess.scoreTime') + ':' + row.scoreStart + '~' + row.scoreEnd + ',' + this.$t('baseAssess.notContainScoreTime')).then(_ => {})
          return
        }
        // this.dialogMode = 'score';
        const response = await graduateStudentApi.queryBaseAndAssessDetail({
          "baseExamineId": row.id,
          "account": this.userInfo.uid
        })
        if (response.code === 200) {
          this.expertsScoreInfo = response.data
        }
        this.scoreDialogVisible = true
      }
      
    },
    // 关闭评分弹出框前的回调
    beforeCloseScore() {
      this.$refs['expertsScore'].back()
    },
    // 关闭评分弹出框
    closeScoreDialog() {
      this.$refs['expertsScore'].fileList = []
      // this.$refs['expertsScore'].scoreForm.specialistComment = ''
      this.$refs['expertsScore'].$refs['scoreForm'].resetFields()
      this.scoreDialogVisible = false
      this.onSubmit()
    },
    // 查看基地考核评分详情--表格
    async selectBaseAssessScoreDetail(row) {
      const response = await graduateStudentApi.queryBaseAssessAndSpecialDetail({
        "id": row.id,
        "templateId": row.templateId
      })
      if (response.code === 200) {
        this.detailScoreAssessBaseInfo = response.data
      }
      this.detailScoreDialogVisible = true;
    },
    // 查看基地考核详情--表格
    async selectBaseAssessDetail(row) {
      this.scoreStatus = row.status
      const response = await graduateStudentApi.queryBaseAssessAndSpecialDetail({
        "id": row.id,
        "templateId": row.templateId
      })
      if (response.code === 200) {
        this.detailAssessBaseInfo = response.data
      }
      this.detailDialogVisible = true
    },
    // 关闭评分详情窗口
    closeScoreDetailDialog() {
      this.detailScoreDialogVisible = false
    },
    // 关闭详情窗口
    closeDetailDialog() {
      this.detailDialogVisible = false
    },
    formDownload(options) {
      let config = options
      let iframe = document.createElement('iframe')
      iframe.style.display = "none";
      iframe.setAttribute('id', 'down-file-iframe')
      let form = document.createElement('form')
      form.style.display = "none";
      form.setAttribute('id', 'downloadForm')
      form.setAttribute('target', 'down-file-iframe')
      form.setAttribute('method', config.method)
      form.setAttribute('action', window.location.origin + config.url)
      iframe.append(form)
      document.body.append(iframe)
      document.getElementById('downloadForm').submit()
      iframe.remove()
    },
    // 详情页-导出
    exportBaseAssessDetail(val) {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      graduateStudentApi.validateSpecialScoreDetail(val).then(res => {
        if (res.code === 200) {
          this.exportResult = null
          this.$refs.downloadRef.open()
          this.exportButton = true
          setTimeout(() => {
            this.formDownload({
              url: "/api/practiceservice/baseGrade/examine/export/zip?id=" + val.id + '&templateId=' + val.templateId,
              method: "post"
            })
            this.exportResult = ''
            this.exportButton = false
            this.$message.success(this.$t('result.exportSuccessfully'))
            this.$refs.downloadRef.close()
          }, 2000)
        }
      })
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-baseAssess-export') {
              this.permitToExport = true
            }
            if (item.authCode === 'graduateStu-baseAssess-edit') {
              this.permitToEdit = true
            }
            if (item.authCode === 'graduateStu-baseAssess-score') {
              this.permitToScore = true
            }
            if (item.authCode === 'graduateStu-baseAssess-scoreDetails') {
              this.permitToScoreDetail = true
            }
            if (item.authCode === 'graduateStu-baseAssess-details') {
              this.permitToDetail = true
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
    
  }
}
</script>
<style lang="scss" scoped>
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }
  .status-container ::v-deep {
    .el-button {
      cursor: auto;
    }
    .el-button--danger {
      padding: 9px 15px;
      min-width: 0;
    }
  }
  .base-assess-set-dialog ::v-deep {
    .el-dialog__body {
      padding-top: 20px!important;
      word-break: break-all!important;
    }
  }
</style>
